package com.weakteam.orderonline.dataresource.domain;

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.persistence.*;
import java.io.Serializable;

/**
 * @author Nail
 */

@Entity
@javax.persistence.Table(name = "\"CLIENT_ORDER_CONTENT\"")
public class ClientOrderContent implements Serializable {

    private static final Logger log = LoggerFactory.getLogger(Goods.class);

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "\"CLIENT_ORDER_CONTENT_id_seq\"")
    @SequenceGenerator(name = "\"CLIENT_ORDER_CONTENT_id_seq\"", sequenceName = "\"CLIENT_ORDER_CONTENT_id_seq\"")
    @Column(name = "\"id\"", nullable = false)
    private Integer id;

    @ManyToOne(optional = false)
    @JoinColumn(name = "\"clientOrderId\"", nullable = false)
    private ClientOrder clientOrder;

    @ManyToOne(optional = false)
    @JoinColumn(name = "\"goodsId\"")
    private Goods goods;

    @Column(name = "\"count\"", nullable = false)
    private Integer count;


    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public ClientOrder getClientOrder() {
        return clientOrder;
    }

    public void setClientOrder(ClientOrder clientOrder) {
        this.clientOrder = clientOrder;
    }

    public Goods getGoods() {
        return goods;
    }

    public void setGoods(Goods goods) {
        this.goods = goods;
    }

    public Integer getCount() {
        return count;
    }

    public void setCount(Integer count) {
        this.count = count;
    }

    public void setJSON(String json) {
        if (json!=null && json.length() > 0){
            try {
                JSONParser parser = new JSONParser();
                JSONObject jObj = (JSONObject)parser.parse(json);
                this.setJSON(jObj);
            } catch (ParseException e) {
                log.error("try to parse json" + e);
            }
        }
    }

    public void setJSON(JSONObject jObj) {
        Object obj = null;
        obj = jObj.get("goodsId");
        if (obj != null) {
            Integer id = ((Long)obj).intValue();
            this.goods = new Goods();
            this.goods.setId(id);
        }
        obj = jObj.get("count");
        if (obj != null) {
            this.count = ((Long) obj).intValue();
        }
    }

    public String getJSON() {
        StringBuilder json = new StringBuilder();
        json.append("{\"count\":").append(count).append(",");
        json.append("\"goodsName\":\"").append(goods.getName()).append("\",");
        json.append("\"itemCost\":").append(goods.getPrice()*count).append("}");
        return json.toString();
    }

}